import pgzrun
import random
import time

ROWS = 50
COLS = 50
CELL_SIZE = 15

HEIGHT = (ROWS * CELL_SIZE)
WIDTH  = (COLS * CELL_SIZE)

BACK_COLOR = (0, 0, 127)
CELL_COLOR = (0, 200, 0)

def init_map(rows, cols):
    return [[0 for c in range(cols)] for r in range(rows)]

world = init_map(ROWS, COLS)
next_world = init_map(ROWS, COLS)

def random_map(w):
    for r in range(ROWS):
        for c in range(COLS):
            w[r][c] = int(random.randint(0, 7) == 0)
def draw_cell(r, c):
    cx = CELL_SIZE * c
    cy = CELL_SIZE * r
    cell_rect = Rect((cx, cy), (CELL_SIZE, CELL_SIZE))
    screen.draw.filled_rect(cell_rect, CELL_COLOR)

def count_neighbors(w, r, c):
    ssum = 0
    for nr in range(r - 1, r + 1 + 1):
        for nc in range(c - 1, c + 1 + 1):
            if nr == r and nc == c:
                continue

            if nr >= ROWS and nr >= COLS:
                if w[nr - ROWS + 1][nc - COLS + 1]:
                    ssum += 1
                continue
            
            
            if nr >= ROWS:
                if w[nr-ROWS + 1][nc]:
                    ssum += 1
                continue

            if nc >= COLS:
                if w[nr][nc - COLS + 1]:
                    ssum += 1
                continue

            if w[nr][nc]:
                ssum += 1

    return ssum

def next_cell(w, r, c):
    n = count_neighbors(w, r, c)

    if n == 3:
        return 1
    elif n == 2:
        return w[r][c]
    else:
        return 0


def update():
    for r in range(ROWS):
        for c in range(COLS):
            next_world[r][c] = next_cell(world, r, c)
    
    for r in range(ROWS):
        for c in range(COLS):
            world[r][c] = next_world[r][c]
            
    time.sleep(0.2)

def draw():
    screen.fill(BACK_COLOR)
    for r in range(ROWS):
        for c in range(COLS):
            if world[r][c]:
                draw_cell(r, c)

random_map(world)
print(world)
pgzrun.go()
